package com.dingreading.cloud.admin.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dingreading.cloud.admin.dto.*;
import com.dingreading.cloud.admin.entity.*;
import com.dingreading.cloud.admin.service.*;
import com.dingreading.cloud.admin.util.bean.GoodsV3Util;
import com.dingreading.cloud.admin.util.bean.OrderFormV3Util;
import com.dingreading.cloud.admin.util.redis.RedisService;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.util.*;
import com.dingreading.cloud.common.util.excel.ExcelHandler;
import com.google.common.collect.Lists;
import com.mybatisflex.core.paginate.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/system/goods/v3")
@Api(tags = "总部-商品管理V3")
public class GoodsControllerV3 {

    @Resource
    protected GoodsService goodsService;
    @Resource
    protected GoodsImgService goodsImgService;
    @Resource
    protected GoodsTypeService goodsTypeService;
    @Resource
    protected GoodsUnitService goodsUnitService;
    @Resource
    protected GoodsCategoryLogService goodsCategoryLogService;
    @Resource
    protected GoodsTypeComboService goodsTypeComboService;
    @Resource
    protected WhStockInService stockInService;
    @Resource
    protected ShopCartService shopCartService;
    @Resource
    protected WhPurchaseGoodsService purchaseGoodsService;
    @Resource
    protected FreeDeliveryService freeDeliveryService;
    @Resource
    protected RedisService redisService;


    @ApiOperation(value = "分页列表")
    @PostMapping(value = "/pageList", produces = "application/json; charset=UTF-8")
    public R<Object> pageList(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "分页公共类") PageUtil pageUtil,
            @ApiParam(value = "商品名") @RequestParam(value = "name", required = false) String name,
            @ApiParam(value = "商品种类id") @RequestParam(value = "categoryId", required = false) Long categoryId,
            @ApiParam(value = "是否禁用 1.启用 0.禁用") @RequestParam(value = "enabled", required = false) Integer enabled,
            @ApiParam(value = "是否实体货物 0.不是 1.是") @RequestParam(value = "realStatus", required = false) Integer realStatus
    ) {
        Page<Goods> pageList = goodsService.pageListV3(pageUtil, name, categoryId, enabled, realStatus);

        PageBeanDto data = new PageBeanDto();
        data.setTotal(pageList.getTotalRow());
        data.setList(pageList.getRecords());
        return R.ok(data);
    }


    @ApiOperation(value = "添加/编辑正常商品或组合商品")
    @PostMapping(value = "/editBean", produces = "application/json; charset=UTF-8")
    public R<Object> editBean(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "商品id") @RequestParam(value = "id", required = false) Long id,
            @ApiParam(value = "商品名") @RequestParam(value = "name") String name,
            @ApiParam(value = "商品原价") @RequestParam(value = "price") Double price,
            @ApiParam(value = "最低购买数") @RequestParam(value = "minBuyNum") Integer minBuyNum,
            @ApiParam(value = "起购数量") @RequestParam(value = "minBuyCnt") Integer minBuyCnt,
            @ApiParam(value = "采购倍数") @RequestParam(value = "buyTimes") Integer buyTimes,
            @ApiParam(value = "商品种类集合[id:0,categoryId：0,categoryName:'']") @RequestParam(value = "categoryList") String categoryList,
            @ApiParam(value = "封面图") @RequestParam(value = "img") String img,
            @ApiParam(value = "是否爆款 0.不是 1.是") @RequestParam(value = "hotStatus") Integer hotStatus,
            @ApiParam(value = "是否实体货物 0.不是 1.是") @RequestParam(value = "realStatus") Integer realStatus,
            @ApiParam(value = "能否使用代金券 0.否 1.能") @RequestParam(value = "couponStatus") Integer couponStatus,
            @ApiParam(value = "上架状态 1.上架 0.下架") @RequestParam(value = "enabled") Integer enabled,
            @ApiParam(value = "付款方式 1.不限 2.银行转账") @RequestParam(value = "paymentMethod") Integer paymentMethod,
            @ApiParam(value = "包邮模板id") @RequestParam(value = "freeDeliveryId") Long freeDeliveryId,
            @ApiParam(value = "商品简介") @RequestParam(value = "intro", required = false) String intro,
            @ApiParam(value = "商品详情") @RequestParam(value = "details", required = false) String details,
            @ApiParam(value = "商品图片") @RequestBody(required = false) List<GoodsImg> imgList
    ) throws Exception {
        // 判断商品信息是否符合规范
        String msg = judgeGoodsInfo(
                name, price, minBuyNum, minBuyCnt, buyTimes, enabled, couponStatus, paymentMethod, freeDeliveryId,
                img, categoryList, imgList
        );
        if (StringUtils.isNotBlank(msg))
            return R.fail(msg);

        // 商品种类
        List<GoodsCategoryLog> categoryLogList = JSONArray.parseArray(categoryList, GoodsCategoryLog.class);
        if (CollectionUtils.isEmpty(categoryLogList))
            return R.fail("商品种类解析失败");

        for (GoodsCategoryLog goodsCategoryLog : categoryLogList) {
            Long categoryId = goodsCategoryLog.getCategoryId();
            if (null == categoryId || categoryId <= 0)
                return R.fail("商品种类id为空");
            String categoryName = goodsCategoryLog.getCategoryName();
            if (StringUtils.isBlank(categoryName))
                return R.fail("商品种类名称为空");
        }

        // 商品图片集合
        for (GoodsImg goodsImg : imgList) {
            if (StringUtils.isBlank(goodsImg.getImg()))
                return R.fail("图片集合未发现图片");
        }

        boolean exist = goodsService.haveName(id, name);
        if (exist)
            return R.fail("商品名称重复了");

        FreeDelivery freeDelivery = freeDeliveryService.getById(freeDeliveryId);
        if (freeDelivery == null)
            return R.fail("包邮模板获取失败");
        if (!freeDelivery.getEnabled().equals(1))
            return R.fail("包邮模板已禁用");

        Goods goods = null;
        if (id == null || id <= 0) {
            // 新增
            // 获取种类的id与名称
            GoodsCategoryDto goodsCategoryDto = GoodsV3Util.getCategoryIdsAndNames(categoryLogList);
            String categoryIds = goodsCategoryDto.getCategoryIds();
            String categoryNames = goodsCategoryDto.getCategoryNames();

            // 保存商品基础信息
            goods = GoodsV3Util.newGoods(new Goods(), headStaffUid, headStaffName, name, intro, details, minBuyNum,
                    minBuyCnt, buyTimes, price, categoryIds, categoryNames, img, hotStatus, couponStatus, enabled,
                    realStatus, paymentMethod, freeDeliveryId);
            goodsService.saveOrUpdate(goods);

            if (goods.getId() <= 0)
                return R.fail("商品信息保存失败");

            // 保存商品种类，并设置商品种类的序号
            GoodsV3Util.newCategoryLogs(categoryLogList, goods.getId());
            goodsCategoryLogService.saveOrUpdateBatch(categoryLogList);

            // 保存商品图片集合
            GoodsV3Util.newGoodsImgs(imgList, goods.getId());
            goodsImgService.saveOrUpdateBatch(imgList);
        } else {
            // 修改
            Long goodsId = id;
            goods = goodsService.getById(goodsId);
            if (null == goods)
                return R.fail("商品获取失败");

            // 重设商品在分类下的排序
            GoodsCategoryDto goodsCategoryDto = GoodsV3Util.setCategoryIdsAndNamesAndIdsAndNewList(categoryLogList, goodsId);
            String categoryIds = goodsCategoryDto.getCategoryIds();
            String categoryNames = goodsCategoryDto.getCategoryNames();
            List<Long> categoryLogIds = goodsCategoryDto.getCategoryLogIds();
            List<GoodsCategoryLog> newCategoryList = goodsCategoryDto.getNewCategoryList();
            // 先删除不需要的商品种类
            goodsCategoryLogService.dropByGoodsIdAndIdsNot(goodsId, categoryLogIds);
            if (CollectionUtils.isNotEmpty(newCategoryList))
                goodsCategoryLogService.saveOrUpdateBatch(newCategoryList);

            // 需要删除的阿里云文件路径
            // 获取商品要删除的封面图片和商品详情内的图片
            List<String> ossFileUrls = GoodsV3Util.getDeleteImgAndDetails(goods, img, details);

            // 处理商品图片集合
            dealGoodsImg(imgList, ossFileUrls, goodsId);

            // 保存商品基础信息
            GoodsV3Util.newGoods(goods, headStaffUid, headStaffName, name, intro, details, minBuyNum, minBuyCnt, buyTimes,
                    price, categoryIds, categoryNames, img, hotStatus, couponStatus, enabled, realStatus,
                    paymentMethod, freeDeliveryId);
            goodsService.saveOrUpdate(goods);

            // 删除阿里云上存储的文件
            GoodsV3Util.deleteOssFiles(ossFileUrls);
        }

        // 清除商城商品种类
        redisService.setNullLike(RedisParam.MALL_CATEGORY);
        return R.ok(goods.getId());
    }


    @ApiOperation(value = "获取商品详情")
    @PostMapping(value = "/getBean", produces = "application/json; charset=UTF-8")
    public R<Object> getBean(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "id") @RequestParam(value = "id") Long id
    ) {
        Goods goods = goodsService.getDataById(id);
        if (goods == null) return R.fail("获取失败");

        if (StringUtils.isNotBlank(goods.getCooperationType())) {
            List<Integer> asList = Arrays.stream(StringUtils.split(goods.getCooperationType(), ","))
                    .map(Integer::parseInt).collect(Collectors.toList());
            goods.setCooperationTypes(asList);
        }

        List<GoodsCategoryLog> logList = goodsCategoryLogService.getByGoodsId(id);
        goods.setCategoryList(logList);

        List<GoodsImg> imgList = goodsImgService.getByGoodsId(id);
        goods.setImgList(imgList);

        return R.ok(goods);
    }


    @ApiOperation(value = "获取商品的规格集合")
    @PostMapping(value = "/getGoodsTypeList", produces = "application/json; charset=UTF-8")
    public R<Object> getGoodsTypeList(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "商品id") @RequestParam(value = "id") Long id
    ) {
        Goods goods = goodsService.getById(id);
        if (goods == null)
            return R.fail("商品获取失败");

        List<GoodsTypeInfoDto> typeList = goodsTypeService.typeInfoListByGoodsIdAndEnabled(id);
        if (CollectionUtils.isNotEmpty(typeList)) {
            Set<Long> typeIds = new HashSet<>();
            Set<Long> comboTypeIds = new HashSet<>();

            for (GoodsTypeInfoDto dto : typeList) {
                if (dto.getComboType().equals(0))
                    typeIds.add(dto.getId());
                else
                    comboTypeIds.add(dto.getId());
            }

            // 查询组合商品的子商品信息
            Map<Long, List<GoodsTypeComboDto>> comboMap = new HashMap<>();
            if (CollectionUtils.isNotEmpty(comboTypeIds)) {
                List<GoodsTypeComboDto> goodsTypeComboList = goodsTypeComboService.dtoListByMainGoodsTypeIds(new ArrayList<>(comboTypeIds));
                if (CollectionUtils.isNotEmpty(goodsTypeComboList)) {
                    comboMap = goodsTypeComboList.stream().collect(Collectors.groupingBy(GoodsTypeComboDto::getMainGoodsTypeId, LinkedHashMap::new, Collectors.toList()));

                    List<Long> childGoodsTypeIds = goodsTypeComboList.stream().map(GoodsTypeComboDto::getGoodsTypeId).collect(Collectors.toList());
                    typeIds.addAll(childGoodsTypeIds);
                }
            }

            // 商品规格的库存数量
            Map<Long, Integer> stockNumMap = new HashMap<>();
            // 商品规格的待发货数量
            Map<Long, Integer> waitSendNumMap = new HashMap<>();
            if (CollectionUtils.isNotEmpty(typeIds)) {
                List<Long> goodsTypeIds = new ArrayList<>(typeIds);
                stockNumMap = stockInService.getStockNumMap(goodsTypeIds);
                waitSendNumMap = shopCartService.getWaitSendNum(goodsTypeIds);
            }

            for (GoodsTypeInfoDto dto : typeList) {
                Long typeId = dto.getId();
                if (dto.getComboType().equals(0)) {
                    // 正常商品
                    int stockNum = OrderFormV3Util.getGoodsTypeNum(stockNumMap.get(typeId), waitSendNumMap.get(typeId));
                    dto.setStockNum(stockNum);
                } else {
                    // 组合商品
                    List<GoodsTypeComboDto> comboDtoList = comboMap.get(dto.getId());
                    // 获取组合商品的最低可售数量和总重量
                    ComboGoodsTypeDto comboGoodsTypeDto = GoodsV3Util.getComboGoodsTypeDto(comboDtoList, stockNumMap, waitSendNumMap);
                    dto.setStockNum(comboGoodsTypeDto.getSaleNum());
                    dto.setWeight(comboGoodsTypeDto.getWeight());

                    dto.setComboList(comboDtoList);
                }
            }
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("goodsName", goods.getName());
        jsonObject.put("goodsTypeList", typeList);
        return R.ok(jsonObject);
    }


    @ApiOperation(value = "修改商品启用状态")
    @PostMapping(value = "/updateEnabled", produces = "application/json; charset=UTF-8")
    public R<Object> updateEnabled(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "id") @RequestParam(value = "id") Long id,
            @ApiParam(value = "启用状态 0.禁用 1.启用") @RequestParam(value = "enabled") Integer enabled
    ) {
        Goods goods = goodsService.getById(id);
        if (goods == null)
            return R.fail("商品获取失败");

        boolean b = goodsService.updateEnabledV3(id, enabled, headStaffUid, headStaffName);
        if (!b)
            return R.fail("更新失败");

        // 商品下架，取消购物车记录
        if (enabled.equals(0))
            shopCartService.cancelShopCartByGoodsId(id);

        // 清除商城商品种类
        redisService.setNullLike(RedisParam.MALL_CATEGORY);
        return R.ok();
    }


    @ApiOperation(value = "删除商品")
    @PostMapping(value = "/dropBean", produces = "application/json; charset=UTF-8")
    public R<Object> dropBean(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "id") @RequestParam(value = "id") Long id
    ) {
        Goods goods = goodsService.getById(id);
        if (null == goods)
            return R.fail("获取失败");

        // 判断商品规格是否被使用
        String msg = GoodsV3Util.judgeUseGoods(id);
        if (StringUtils.isNotBlank(msg))
            return R.fail(msg);

        List<GoodsType> goodsTypeList = goodsTypeService.getByGoodsId(id);
        List<GoodsImg> goodsImgList = goodsImgService.getByGoodsId(id);

        // 删除商品规格
        goodsTypeService.deleteByGoodsIdAndIds(id, null);
        // 删除商品组合
        goodsTypeComboService.deleteByMainGoodsId(id);
        // 删除商品
        goodsService.dropBean(id);
        // 删除商品图片
        goodsImgService.deleteByGoodsIdAndIds(id, null);
        // 删除商品种类记录
        goodsCategoryLogService.dropByGoodsIdAndIdsNot(id, null);

        List<String> fileUrls = new ArrayList<>();
        // 封面图
        String img = goods.getImg();
        if (StringUtils.isNotBlank(img)) {
            fileUrls.add(GoodsV3Util.getOssFileUrl(img));
        }
        // 商品详情富文本
        String details = goods.getDetails();
        if (StringUtils.isNotBlank(details) && details.contains("<img src=")) {
            String[] urls = GoodsV3Util.getDetailsOssFileUrls(details);
            if (null != urls && urls.length > 0) {
                fileUrls.addAll(Arrays.asList(urls));
            }
        }
        // 商品规格图片
        if (CollectionUtils.isNotEmpty(goodsTypeList)) {
            for (GoodsType goodsType : goodsTypeList) {
                String goodsTypeImg = goodsType.getImg();
                if (StringUtils.isNotBlank(goodsTypeImg))
                    fileUrls.add(GoodsV3Util.getOssFileUrl(goodsTypeImg));
            }
        }
        // 商品图片集合
        if (CollectionUtils.isNotEmpty(goodsImgList)) {
            for (GoodsImg goodsImg : goodsImgList) {
                String goodImg = goodsImg.getImg();
                if (StringUtils.isNotBlank(goodImg))
                    fileUrls.add(GoodsV3Util.getOssFileUrl(goodImg));
            }
        }

        // 删除阿里云上存储的文件
        GoodsV3Util.deleteOssFiles(fileUrls);

        // 清除商城商品种类
        redisService.setNullLike(RedisParam.MALL_CATEGORY);
        return R.ok();
    }


    @ApiOperation(value = "上移/下移")
    @PostMapping(value = "/upOrDown", produces = "application/json; charset=UTF-8")
    public R<Object> upOrDown(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "商品id") @RequestParam(value = "id") Long id,
            @ApiParam(value = "商品种类id") @RequestParam(value = "categoryId") Long categoryId,
            @ApiParam(value = "类型 1.上移 2.下移") @RequestParam(value = "type") Integer type
    ) {
        if (categoryId == null || categoryId <= 0)
            return R.fail("请先选择商品种类");

        GoodsCategoryLog data = goodsCategoryLogService.getByGoodsIdAndCategoryId(id, categoryId);
        if (data == null)
            return R.fail("商品种类排序记录获取失败");

        if (type.equals(1)) {
            // 上移
            GoodsCategoryLog preData = goodsCategoryLogService.getLtShowOrder(categoryId, data.getOrderNum());
            if (preData == null)
                return R.fail("已在最前");
            // 和前一条记录的序号互换
            Integer prevOrderNum = preData.getOrderNum();
            Integer curOrderNum = data.getOrderNum();
            // 序号互换
            goodsCategoryLogService.updateShowOrder(preData.getId(), curOrderNum);
            goodsCategoryLogService.updateShowOrder(data.getId(), prevOrderNum);
        } else if (type.equals(2)) {
            // 下移
            GoodsCategoryLog backData = goodsCategoryLogService.getGtShowOrder(categoryId, data.getOrderNum());
            if (backData == null)
                return R.fail("已在最后");
            // 和后一条记录的序号互换
            Integer backOrderNum = backData.getOrderNum();
            Integer curOrderNum = data.getOrderNum();
            // 序号互换
            goodsCategoryLogService.updateShowOrder(backData.getId(), curOrderNum);
            goodsCategoryLogService.updateShowOrder(data.getId(), backOrderNum);
        } else {
            return R.fail("类型错误");
        }

        goodsService.updateLastStaffInfo(id, headStaffUid, headStaffName);

        return R.ok();
    }


    @ApiOperation(value = "商品置顶")
    @PostMapping(value = "/setTop", produces = "application/json; charset=UTF-8")
    public R<Object> setTop(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "商品id") @RequestParam(value = "id") Long id,
            @ApiParam(value = "商品种类id") @RequestParam(value = "categoryId") Long categoryId
    ) {
        if (categoryId == null || categoryId <= 0)
            return R.fail("请先选择商品种类");

        GoodsCategoryLog data = goodsCategoryLogService.getByGoodsIdAndCategoryId(id, categoryId);
        if (data == null)
            return R.fail("商品种类排序记录获取失败");

        GoodsCategoryLog topGoods = goodsCategoryLogService.getTopOrder(categoryId);
        if (topGoods == null)
            return R.fail("置顶商品排序记录获取失败");

        if (data.getOrderNum().equals(topGoods.getOrderNum()))
            return R.fail("已在最前");

        // 和置顶商品的序号互换
        Integer topOrderNum = topGoods.getOrderNum();
        // 设置置顶
        goodsCategoryLogService.updateShowOrder(data.getId(), topOrderNum);
        // 种类下其他商品序号+1
        goodsCategoryLogService.updateOtherOrderAddOne(data.getId(), categoryId);

        goodsService.updateLastStaffInfo(id, headStaffUid, headStaffName);

        return R.ok();
    }


    @ApiOperation(value = "获取商品的单位")
    @PostMapping(value = "/getGoodsUnits", produces = "application/json; charset=UTF-8")
    public R<Object> getGoodsUnits(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName
    ) {
        List<GoodsUnit> list = goodsUnitService.getByEnabled(1);

        return R.ok(list);
    }


    @ApiOperation(value = "导出叮叮书籍和四大名著的采购金额和售出金额")
    @PostMapping(value = "/exportGoodsPurchaseAndSaleAmount", produces = "application/json; charset=UTF-8")
    public void exportGoodsPurchaseAndSaleAmount(
            HttpServletResponse response
    ) throws Exception {
        List<Goods> goodsList = goodsService.listByCategoryIdOrIdIn(",7,", Arrays.asList(110L, 51L, 52L));
        if (CollectionUtils.isEmpty(goodsList))
            throw new DescribeException("未查询到商品");

        Map<Long, Goods> goodsMap = goodsList.stream().collect(Collectors.toMap(Goods::getId, Function.identity()));

        List<GoodsType> goodsTypeList = goodsTypeService.listByGoodsIdIn(Lists.newArrayList(goodsMap.keySet()));
        if (CollectionUtils.isEmpty(goodsTypeList))
            throw new DescribeException("未查询到商品规格");

        List<Long> goodsTypeIds = goodsTypeList.stream().map(GoodsType::getId).collect(Collectors.toList());

        // 商品采购记录
        List<WhPurchaseGoods> purchaseGoodsList = purchaseGoodsService.listByGoodsTypeIdIn(goodsTypeIds);
        Map<Long, List<WhPurchaseGoods>> purchaseGoodsMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(purchaseGoodsList)) {
            purchaseGoodsMap = purchaseGoodsList.stream().collect(Collectors.groupingBy(WhPurchaseGoods::getGoodsTypeId));
        }

        // 商品售出记录
        List<ShopCart> shopCartList = shopCartService.saleListByGoodsTypeIdIn(goodsTypeIds);
        Map<Long, Map<String, List<ShopCart>>> shopCartMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(shopCartList)) {
            shopCartMap = shopCartList.stream().collect(Collectors.groupingBy(ShopCart::getGoodsTypeId,
                    Collectors.groupingBy(cart -> {
                        if (cart.getCorpUid().equals(AccountUtil.SELF_CORP_UID)) {
                            return "self";
                        } else {
                            return "join";
                        }
                    })));
        }

        List<PurchaseAndSalePriceVO> voList = new ArrayList<>();
        for (GoodsType goodsType : goodsTypeList) {
            Long goodsTypeId = goodsType.getId();

            Goods goods = goodsMap.get(goodsType.getGoodsId());

            double purchasePrice = 0d;
            int purchaseNum = 0;
            List<WhPurchaseGoods> purchaseGoods = purchaseGoodsMap.get(goodsTypeId);
            if (CollectionUtils.isNotEmpty(purchaseGoods)) {
                for (WhPurchaseGoods purchaseGood : purchaseGoods) {
                    // 调库记录不计算
                    if (purchaseGood.getPrice() > 0) {
                        purchaseNum += purchaseGood.getBuyNum();
                        purchasePrice = DoubleUtil.sum(purchasePrice, purchaseGood.getPrice());
                    }
                }
            }

            int selfBuyNum = 0;
            int joinBuyNum = 0;
            double selfSalePrice = 0d;
            double joinSalePrice = 0d;
            Map<String, List<ShopCart>> corpCartMap = shopCartMap.get(goodsTypeId);
            if (corpCartMap != null && !corpCartMap.isEmpty()) {
                List<ShopCart> selfCarts = corpCartMap.get("self");
                List<ShopCart> joinCarts = corpCartMap.get("join");
                if (CollectionUtils.isNotEmpty(selfCarts)) {
                    for (ShopCart cart : selfCarts) {
                        selfBuyNum += cart.getBuyNum();
                        selfSalePrice = DoubleUtil.sum(selfSalePrice, cart.getPrice());
                    }
                }
                if (CollectionUtils.isNotEmpty(joinCarts)) {
                    for (ShopCart cart : joinCarts) {
                        joinBuyNum += cart.getBuyNum();
                        joinSalePrice = DoubleUtil.sum(joinSalePrice, cart.getPrice());
                    }
                }
            }

            double salePrice = DoubleUtil.sum(selfSalePrice, joinSalePrice);
            PurchaseAndSalePriceVO vo = new PurchaseAndSalePriceVO();
            vo.setGoodsName(goods.getName());
            vo.setGoodsTypeName(goodsType.getName());
            vo.setPurchaseNum(purchaseNum);
            vo.setPurchaseAmount(purchasePrice);
            vo.setBuyNum(selfBuyNum + joinBuyNum);
            vo.setCartAmount(salePrice);
            vo.setSelfBuyNum(selfBuyNum);
            vo.setSelfCartAmount(selfSalePrice);
            vo.setJoinBuyNum(joinBuyNum);
            vo.setJoinCartAmount(joinSalePrice);

            voList.add(vo);
        }

        String fileName = "商品的采购价格和售出价格";
        ExcelHandler.exportExcel(response, voList, PurchaseAndSalePriceVO.class, fileName, "商品的采购价格和售出价格", true);
    }

    /**
     * 处理商品图片集合
     */
    private void dealGoodsImg(List<GoodsImg> goodsImgList, List<String> ossFileUrls, Long goodsId) {
        // 更新商品图片
        List<Long> updateImgIds = new ArrayList<>();
        // 修改商品图片集合
        List<GoodsImg> newImgList = new ArrayList<>();
        for (int i = 0; i < goodsImgList.size(); i++) {
            GoodsImg goodsImg = goodsImgList.get(i);
            if (null == goodsImg.getId() || goodsImg.getId() <= 0) {
                // 添加新图片
                goodsImg.setGoodsId(goodsId);
            } else {
                // 更新图片
                updateImgIds.add(goodsImg.getId());
            }
            goodsImg.setOrderNum(i + 1);
            newImgList.add(goodsImg);
        }
        // 获取将要删除的图片的阿里云文件路径
        List<GoodsImg> delGoodsImgList = goodsImgService.getByGoodsIdAndIdsNot(goodsId, updateImgIds);
        if (CollectionUtils.isNotEmpty(delGoodsImgList)) {
            for (GoodsImg goodsImg : delGoodsImgList) {
                String goodImg = goodsImg.getImg();
                if (StringUtils.isNotBlank(goodImg))
                    ossFileUrls.add(GoodsV3Util.getOssFileUrl(goodImg));
            }
            // 删除不要的数据
            goodsImgService.deleteByGoodsIdAndIdsNot(goodsId, updateImgIds);
        }
        // 新增或更新数据
        goodsImgService.saveOrUpdateBatch(newImgList);
    }

    /**
     * 判断商品信息是否符合规范
     */
    private String judgeGoodsInfo(
            String name, Double price, Integer minBuyNum, Integer minBuyCnt, Integer buyTimes, Integer enabled,
            Integer couponStatus, Integer paymentMethod, Long freeDeliveryId,
            String img, String categoryList, List<GoodsImg> imgList
    ) {
        if (StringUtils.isBlank(name))
            return "填写正确的商品名称";
        if (null == price || price <= 0)
            return "填写正确的商品单价";
        if (null == minBuyNum || minBuyNum <= 0)
            return "最低购买数不能为0";
        if (null == minBuyCnt || minBuyCnt <= 0)
            return "请填写正确的起购数量";
        if (null == buyTimes || buyTimes <= 0)
            return "请填写正确的采购倍数";
        if (null == enabled)
            return "请选择上架状态";
        if (null == couponStatus)
            return "请选择能否使用代金券";
        if (StringUtils.isBlank(img))
            return "请添加封面图";
        if (null == paymentMethod)
            return "请选择付款方式";
        if (!paymentMethod.equals(1) && !paymentMethod.equals(2))
            return "付款方式标识错误";
        if (null == freeDeliveryId || freeDeliveryId <= 0)
            return "请选择包邮模板";
        if (StringUtils.isBlank(categoryList))
            return "请选择商品种类";
        if (CollectionUtils.isEmpty(imgList))
            return "请添加图片集合";


        return "";
    }


}
